package Reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-15
 * Time: 15:02
 */
public class getConstructionMethod {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //获取字节码文件对象
        Class<?> studentClass = Class.forName("Reflect.Student");

        //通过字节码文件对象获取所有公有构造方法
        Constructor<?>[] constructors = studentClass.getConstructors();
        for (Constructor<?> con:constructors) {
            System.out.println(con);
        }

        //通过字节码文件对象获取某个公有的构造方法
        Student stu1 = new Student();
        Constructor<?> method = studentClass.getConstructor(int.class);
        System.out.println(method.getName());//返回构造器名称

        //通过字节码文件对象获取所有构造方法
        Constructor<?>[] declaredConstructors = studentClass.getDeclaredConstructors();
        for (Constructor<?> con:declaredConstructors) {
            System.out.println(con);
        }

        //通过字节码文件对象获取某个构造方法，包括私有的
        Constructor<?> declaredConstructor = studentClass.getDeclaredConstructor(String.class,int.class);

        //临时解除权限检查
        declaredConstructor.setAccessible(true);

        //通过私有的构造方法创建学生对象
        Student stu3 = (Student)declaredConstructor.newInstance("hao_xiao_zi", 20);
        System.out.println(stu3);

        //使用拿到的构造方法创建学生对象
        Student stu2 = (Student)method.newInstance(20);
        System.out.println(stu2);
    }
}
